package me.cjj.android.assignment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class ResultActivity extends AppCompatActivity {

    public static void start(Context context, boolean[] correct_result, long[] time_cost) {
        Intent starter = new Intent(context, ResultActivity.class);
        starter.putExtra(PARAM_CORRECT_RESULT, correct_result);
        starter.putExtra(PARAM_TIME_COST, time_cost);
        context.startActivity(starter);
    }

    public static final String PARAM_CORRECT_RESULT = "correct_result";
    public static final String PARAM_TIME_COST = "time_cost";

    @SuppressLint("DefaultLocale")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        TextView tvResult = findViewById(R.id.tvResult);
        Bundle extras = getIntent().getExtras();
        if (extras == null) {
            return;
        }
        boolean[] correctResult = (boolean[]) extras.get(PARAM_CORRECT_RESULT);
        long[] timeCost = (long[]) extras.get(PARAM_TIME_COST);
        if (timeCost == null || correctResult == null) {
            return;
        }
        double averageLinear = (average(new long[]{timeCost[0], timeCost[1], timeCost[2], timeCost[3], timeCost[4]}) / 1000);
        double averageQuadratic = average(new long[]{timeCost[5], timeCost[6], timeCost[7], timeCost[8], timeCost[9]}) / 1000;
        int i = 0;
        for (boolean b : correctResult) {
            if (b) {
                i++;
            }
        }
        tvResult.setText(String.format("Correct answer:%d\nThe average time cost of linear equation is %s second\nThe average time cost of quadratic equation is %s second", i, averageLinear, averageQuadratic));
    }

    public double average(long[] array) {
        double sum = 0.0;
        int count = 0;
        for (long l : array) {
            sum += l;
            count += 1;
        }
        return (count == 0) ? Double.NaN : sum / count;
    }
}
